<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" label="查询时间">
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm"
        />
      </el-form-item>
      <el-form-item label="车辆" prop="carNumber">
        <el-tree-select
          v-model="query.carNumber"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="nameType" style="width: 170px; margin-right: 2px;">
          <el-option label="司机" value="driverName" />
          <el-option label="押运员" value="escort" />
        </el-select>
        <el-input v-model="nameText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2">
        <el-col :span="11">
          <el-form-item label="仓库(出)" prop="outStoreId">
            <el-select v-model="query.outStoreId" :loading="$loadingPlugin.getStoreListFn" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in storeList"
                :key="item.storeId"
                :label="item.storeName"
                :value="item.storeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2" class="svg-row">
          <span class="svg-container" @click="transfer">
            <svg-icon icon-class="transfer" class="transfer-icon" color="#1296db" />
          </span>
        </el-col>
        <el-col :span="11">
          <el-form-item label="仓库(入)" prop="inStoreId">
            <el-select v-model="query.inStoreId" :loading="$loadingPlugin.getStoreListFn" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in storeList"
                :key="item.storeId"
                :label="item.storeName"
                :value="item.storeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="类型" prop="loadType">
        <el-select v-model="query.loadType" placeholder="请选择">
          <el-option
            v-for="item in loadTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="loadStatus">
        <el-select v-model="query.loadStatus" placeholder="请选择">
          <el-option
            v-for="item in loadStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据筛选">
        <el-select v-model="query.isTransBill">
          <el-option label="全部单据" :value="-1" />
          <el-option label="仅调拨装卸车单" :value="1" />
          <el-option label="仅手动装车车单" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <el-button-group>
        <el-button type="primary" icon="el-icon-download" :loading="$loadingPlugin.print" @click="print">打印</el-button>
      </el-button-group>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      stripe
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <detail ref="detail" />
  </div>
</template>

<script>
  import { queryLoadVehicleList, queryStoreListAll, queryMap } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import getTreeData from '@/utils/jsonTree'
  import Detail from './components/Detail'

  export default {
    name: 'loadingVehicleManage',
    components: {
      Detail
    },
    data() {
      return {
        treeData: [],
        storeList: [],
        nameType: 'driverName',
        nameText: '',
        date: [moment().startOf('day'), moment().endOf('day')],
        loadTypeMap: [],
        loadStatusMap: [],
        currentOrg: null,
        query: {
          carNumber: '',
          inStoreId: '',
          truckId: '',
          loadType: '',
          loadStatus: '',
          isTransBill: -1
        },
        tableData: {
          data: [],
          column: [
            {
              prop: 'transLoadCode',
              label: '单号',
              width: 120,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.transLoadCode}</el-link>
            },
            {
              prop: 'loadType',
              label: '类型',
              render: (h, { row }) => <span>{ row.loadType && formatColumnMap(this.loadTypeMap, 'value', row.loadType, 'desc') }</span>
            },
            {
              prop: 'createTime',
              label: '时间',
              width: 150,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'inStoreName',
              label: '仓库(出-->入)',
              width: 300,
              render: (h, { row }) => <span>{ row.fromStoreName } -> { row.carNumber }</span>
            },
            {
              prop: 'carNumber',
              label: '车辆'
            },
            {
              prop: 'driverName',
              label: '司机'
            },
            {
              prop: 'escort',
              label: '押运员'
            },
            {
              prop: 'transCheckCode',
              label: '关联单据'
            },
            {
              prop: 'loadStatus',
              label: '状态',
              render: (h, { row }) => <span>{ row.loadStatus && formatColumnMap(this.loadStatusMap, 'value', row.loadStatus, 'desc') }</span>
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getStoreListFn(), this.queryOptionsMap()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        // .orgOption & 0x01 > 0 表示移动门市
        const data = this.orgList.filter(it => it.orgOption & 0x01 > 0).map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.createTime = moment(this.date[0]).format()
          query.createTimeEnd = moment(this.date[1]).format()
        }
        query[this.nameType] = this.nameText
        const res = await queryLoadVehicleList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      handleSelectionChange(val) {
        this.selectedObj = val
      },
      // 查询仓库下拉列表
      async getStoreListFn() {
        const res = await queryStoreListAll({
          reType: 0
        })
        this.storeList = res.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([queryMap({ enumName: 'InvenTransLoadStatus' }), queryMap({ enumName: 'InvenTransLoadType' })])
        this.loadTypeMap = res1.data
        this.loadStatusMap = res2.data
      },
      openDetail(row) {
        this.$refs.detail.open(row, 'detail')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      transfer() {
        const copy = JSON.parse(JSON.stringify(this.query))
        this.query.outStoreId = copy.inStoreId
        this.query.inStoreId = copy.outStoreId
      },
      print() {},
      reset() {
        this.dateType = 'createTime'
        this.date = []
        this.personType = 'createUserId'
        this.personId = ''
        this.query = {
          stockCode: '',
          inStoreId: '',
          truckId: '',
          carrierCode: '',
          stockStatus: ''
        }
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.svg-row {
  text-align: center;
  .svg-container {
    display: inline-block;
    width: 25px;
    cursor: pointer;
    .transfer-icon {
      width: 25px;
      height: 25px;
      vertical-align: middle;
    }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
</style>
